package com.lxy.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 请不要模仿我
 *
 * @author lxy
 * @date 2022/9/30 10:10
 * com.lxy.login.controller.
 */
@Controller
@RequestMapping("/file")
public class FileController {
    @RequestMapping("/upload")
    public String upload(MultipartFile upload, String name, HttpServletRequest request) throws IOException {
        System.out.println(name);
        System.out.println(upload);
        String filename = upload.getOriginalFilename();
        String realPath =  request.getServletContext().getRealPath("/");
        File uploadDir = new File(realPath,"upload");
        if(!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        // 底层 是 IO 流操作
        upload.transferTo(new File(uploadDir,filename));

        request.setAttribute("result","上传成功");
        // 得到上传的目录下的 所有文件的名字  放在集合 传到页面以超链接的形式展示  进行下载
        String[] list = uploadDir.list();

        List<String> fileNames = Arrays.asList(list);
        request.setAttribute("fileNames",fileNames);

        return "result";
    }
    /*
     * 采用file.Transto 来保存上传的文件
     */
    @RequestMapping ( "fileUpload2" )
    public  String  fileUpload2( @RequestParam( "file" ) CommonsMultipartFile file)  throws  IOException {
        long   startTime=System.currentTimeMillis();
        System.out.println( "fileName：" +file.getOriginalFilename());
        String path= "E:/" + new Date().getTime()+file.getOriginalFilename();

        File newFile= new  File(path);
        //通过CommonsMultipartFile的方法直接写文件（注意这个时候）
        file.transferTo(newFile);
        long   endTime=System.currentTimeMillis();
        System.out.println( "采用file.Transto的运行时间：" +String.valueOf(endTime-startTime)+ "ms" );
        return  "/success" ;
    }
}
